package com.zhanggm.student.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhanggm.student.entity.Area;
import com.zhanggm.student.mapper.AreaMapper;
import com.zhanggm.student.model.AreaModel;
import com.zhanggm.student.service.IAreaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhanggm
 * @since 2020-10-21
 */
@Slf4j
@Service
public class AreaServiceImpl extends ServiceImpl<AreaMapper, Area> implements IAreaService {

    @Override
    public List<AreaModel> getAreaAll() {
        //查询所有地区
        List<AreaModel> areaAll = getBaseMapper().getAreaAll();
        return areaAll;
    }


    @Override
    public List<AreaModel> treelist(Integer pid) {
        //查询所有地区
        List<AreaModel> areaAll = getBaseMapper().getAreaAll();
        //查询省列表
        List<AreaModel> areaList = getAreaListByPid(areaAll,pid);
        //递归查询孩子
        getSubArea(areaList, areaAll);
        return areaList;
    }

    /**
     * 根据pid查询地区列表
     * @param areaAll
     * @param pid
     * @return
     */
    @Override
    public List<AreaModel> getAreaListByPid(List<AreaModel> areaAll, Integer pid){
        List<AreaModel> subAreaList = new ArrayList<>();
        for (int i = 0; i < areaAll.size(); i++) {
            AreaModel area = areaAll.get(i);
            if(area.getPid().intValue()==pid.intValue()){
                subAreaList.add(area);
            }
        }
        log.info("subListSize:{}",subAreaList.size());
        return subAreaList;
    }

    /**
     * 递归查询
     * @param areaList
     */
    public void getSubArea(List<AreaModel> areaList,List<AreaModel> areaAll){
        for (int i = 0; i < areaList.size(); i++) {
            AreaModel area = areaList.get(i);
            List<AreaModel> subAreaList = getAreaListByPid(areaAll,area.getId());
            if(subAreaList!=null && subAreaList.size()>0){
                area.setSubArea(subAreaList);
                //递归
                getSubArea(subAreaList,areaAll);
            }
        }
    }
}
